package com.gw2.gw2world.fragment;

import java.io.Serializable;
import java.util.HashMap;

import com.gw2.gw2world.R;
import com.gw2.gw2world.controller.ActiveEventManager;
import com.gw2.gw2world.controller.DatabaseOpenHelper;
import com.gw2.gw2world.controller.EventDownloader;
import com.gw2.gw2world.controller.MapAdapter;
import com.gw2.gw2world.controller.OnTaskCompleted;
import com.gw2.gw2world.controller.RangeSeekbar;
import com.gw2.gw2world.controller.RangeSeekbar.OnRangeSeekBarChangeListener;
import com.gw2.gw2world.controller.Tools;
import com.gw2.gw2world.model.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

/** Display and manage events per map. It can be useful to complete daily as fast as possible.
 * Future improvements:
 * <ul>
 * <li>Choose server home/guest 1-2 or display all</li>
 * <li>Background images</li>
 * <li>Favorite events</li>
 * <li>Special maps for limited events</li>
 * </ul>
 * Known bugs:
 * <ul>
 * <li>Screen rotation lose events</li>
 * </ul>
 */
public class ActiveEventFragment extends Fragment implements OnCheckedChangeListener, OnTaskCompleted, android.content.DialogInterface.OnClickListener, OnRangeSeekBarChangeListener, Serializable {
	private static final long serialVersionUID = 1L;
	private static final String TAG = "ActiveEventFragment";
	private static final long REFRESH_RATE=20000;
	private ListView lv_events;
	private ProgressBar pb_refreshing;
	private RadioGroup rg_maps;
	private RadioButton rb_checked;
	private CheckBox cb_guesting, cb_all, cb_group, cb_lw;
	private DatabaseOpenHelper dbHelper;
	protected SQLiteDatabase db;
	protected Cursor c;
	protected MapAdapter mapAdapter;
	private java.util.Map<String,String> event_names;
	private String language;
	private SharedPreferences prefs;
	private SharedPreferences.Editor editor;
	private Handler handler=new Handler();
	private Runnable task;
	private Dialog mapSelectorDialog;
	private AlertDialog filterDialog;
	private EventDownloader downloader;
	private int map_id=0;
	private ActiveEventManager eventManager;
	//private boolean enableGuesting=false, showGroupEvents=true, showAll=false;
	private View filterView;
	private RangeSeekbar rs_level;
	private TextView tv_level, tv_level_label,tv_map;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Tools.forceLocale(getActivity());
		dbHelper = new DatabaseOpenHelper(getActivity(), "database", null, 1);
		//dbHelper.installLivingWorldEvents();
		db = dbHelper.getReadableDatabase();
		prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
		language = prefs.getString("language", "en");
		mapSelectorDialog = new Dialog(getActivity());
		mapSelectorDialog.setTitle(R.string.select_a_map);
		mapSelectorDialog.setContentView(R.layout.map_selector);
		//init filter dialog
		filterView=getActivity().getLayoutInflater().inflate(R.layout.active_event_filter, null);
		filterDialog=new AlertDialog.Builder(getActivity())
			.setTitle(R.string.filter)
			.setView(filterView)
			.setNegativeButton(android.R.string.cancel, this)
			.setNeutralButton(R.string.save_and_validate, this)
			.setPositiveButton(android.R.string.ok, this).create();
		cb_all=(CheckBox)filterView.findViewById(R.id.cb_ae_allevents);
		cb_all.setChecked(prefs.getBoolean("ae_all", false));
		cb_group=(CheckBox)filterView.findViewById(R.id.cb_ae_group_events);
		cb_group.setChecked(prefs.getBoolean("ae_group", true));
		cb_guesting=(CheckBox)filterView.findViewById(R.id.cb_ae_guesting);
		cb_guesting.setChecked(prefs.getBoolean("ae_guesting", false));
		cb_lw=(CheckBox)filterView.findViewById(R.id.cb_ae_living_world);
		cb_lw.setChecked(prefs.getBoolean("ae_living_world", true));
		rs_level=(RangeSeekbar)filterView.findViewById(R.id.rs_ae_level);
		rs_level.setRange(1, 80);
		rs_level.setOnRangeSeekBarChangeListener(this);
		tv_level=(TextView)filterView.findViewById(R.id.tv_ae_level_filter_values);
		tv_level_label=(TextView)filterView.findViewById(R.id.tv_ae_level_filter);
		eventManager=new ActiveEventManager(getActivity());
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {             
	    View v = inflater.inflate(R.layout.active_events_fragment, container, false);
	    rg_maps=(RadioGroup)mapSelectorDialog.findViewById(R.id.rg_map_selector);
		rg_maps.setOnCheckedChangeListener(this);
		tv_map=(TextView)v.findViewById(R.id.tv_ae_selected_map);
		//events
		lv_events = (ListView) v.findViewById(R.id.lv_active_events);
		//eventAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
		event_names = new HashMap<String, String>();
		//lv_events.setAdapter(eventAdapter);
		lv_events.setAdapter(eventManager);
		//other
		pb_refreshing = (ProgressBar) v.findViewById(R.id.pb_refreshing_active_events);
		//get maps
		//boolean selected = false;
		for (int i = 0; i < mapSelectorDialog.getContext().getResources().getStringArray(R.array.region).length; i++) {
			TextView tv = new TextView(mapSelectorDialog.getContext());
			tv.setText(mapSelectorDialog.getContext().getResources().getStringArray(R.array.region)[i]);
			rg_maps.addView(tv);
			c = db.query("location", null, "region_id=? AND lang=?", new String[] { String.valueOf(i + 1), language },
					null,null, "min_level,max_level");
			Map m;
			while (c.moveToNext()) {
				RadioButton rb = new RadioButton(mapSelectorDialog.getContext());
				rb.setText(c.getString(2));
				m=new Map();
				m.id=c.getInt(0);
				m.min_level=c.getInt(4);
				m.max_level=c.getInt(5);
				rb.setTag(m);
				rg_maps.addView(rb);
			}
		}
		//get events
		c = db.query("event_name", null, "lang=?", new String[] { language }, null, null, null);
		while (c.moveToNext())
			event_names.put(c.getString(0), c.getString(2));
		db.close();
		Tools.lockScreenFromPreferences(getActivity());
	    return v;
	}
	@Override
	public void onPause() {
		if(downloader!=null) downloader.cancel(true);
		mapSelectorDialog.dismiss();
		filterDialog.dismiss();
		handler.removeCallbacksAndMessages(null);
		Tools.unlockScreen(getActivity());
		super.onPause();
	}
	@Override
	public void onResume() {
		android.util.Log.d(TAG, "onResume(): ");
		Tools.lockScreenFromPreferences(getActivity());
		if(downloader!=null && task!=null) start();
		super.onResume();
	}
	@Override
	public void onCheckedChanged(RadioGroup rg, int checkedId) {
		rb_checked=(RadioButton)mapSelectorDialog.findViewById(checkedId);
		if(rb_checked!=null) tv_map.setText(rb_checked.getText());
		mapSelectorDialog.hide();
		Map m=(Map) rb_checked.getTag();
		map_id=m.id;
		rs_level.setRange(m.min_level, m.max_level);
		if(m.min_level==m.max_level) {
			tv_level.setVisibility(View.GONE);
			tv_level_label.setVisibility(View.GONE);
			rs_level.setVisibility(View.GONE);
		} else {
			tv_level.setVisibility(View.VISIBLE);
			tv_level_label.setVisibility(View.VISIBLE);
			rs_level.setVisibility(View.VISIBLE);
		}
		//rs_level.setSelectableRange(m.min_level, m.max_level);
		//android.util.Log.d(TAG, String.valueOf(m.min_level)+" - "+String.valueOf(m.max_level));
		tv_level.setText(String.valueOf(rs_level.getMinSelectedValue())+" - "+String.valueOf(rs_level.getMaxSelectedValue()));
		eventManager.clear();
		start();
	}
	public void selectMap() {mapSelectorDialog.show();}
	public void selectFilter() {filterDialog.show();}
	private void start() {
		if(rb_checked==null) {
			Toast.makeText(getActivity(), R.string.msg_select_map, Toast.LENGTH_SHORT).show();
			return;
		}
		handler.removeCallbacksAndMessages(null);
		downloader=new EventDownloader(getActivity(), prefs.getString("language", "en"),prefs.getInt("home_server", 0),prefs.getInt("guest1_server", 0),prefs.getInt("guest2_server", 0), false);
		downloader.setWorkingView(pb_refreshing);
		downloader.setOnTaskCompletedListener(this);
		downloader.setGuesting(cb_guesting.isChecked());
		downloader.removeInactiveEvents(!cb_all.isChecked());
		downloader.setMap(map_id);
		downloader.setRangeLevel(rs_level.getMinSelectedValue(), rs_level.getMaxSelectedValue());
		downloader.setShowGroupEvents(cb_group.isChecked());
		downloader.setShowLivingStoryEvents(cb_lw.isChecked());
		downloader.execute();
	}
	@Override
	public void onTaskCompleted() {
		eventManager.setGuestingEnabled(cb_guesting.isChecked());
		eventManager.setStatesEnabled(cb_all.isChecked());
		eventManager.clearAndAdd(downloader.getEvents());
		task = new Runnable() {
			@Override
			public void run() {start();}
		};
		handler.postDelayed(task, REFRESH_RATE);
	}
	/*@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==R.id.mi_guesting) {
			item.setChecked(!enableGuesting);
			enableGuesting=item.isChecked();
			start();
		} else if(item.getItemId()==R.id.mi_group_events) {
			item.setChecked(!showGroupEvents);
			showGroupEvents=item.isChecked();
			start();
		} else if(item.getItemId()==R.id.mi_show_disabled) {
			Intent i=new Intent(getActivity(), DisabledActiveEventsActivity.class);
			getActivity().startActivity(i);
		} else if(item.getItemId()==R.id.mi_show_all) {
			item.setChecked(!showAll);
			showAll=item.isChecked();
			start();
		}
		return true;
	}*/
	@Override
	public void onClick(DialogInterface di, int what) {
		if(what==AlertDialog.BUTTON_NEUTRAL) {
			editor=prefs.edit();
			editor.putBoolean("ae_guesting", cb_guesting.isChecked());
			editor.putBoolean("ae_lw", cb_lw.isChecked());
			editor.putBoolean("ae_group", cb_group.isChecked());
			editor.putBoolean("ae_all", cb_all.isChecked());
			editor.commit();
		}
		if(what==AlertDialog.BUTTON_POSITIVE || what==AlertDialog.BUTTON_NEUTRAL)
			start();
		filterDialog.dismiss();
		//filterDialog.hide();
	}
	@Override
	public void onRangeSeekBarValuesChanged(RangeSeekbar bar, int minValue, int maxValue) {
		tv_level.setText(String.valueOf(minValue)+" - "+String.valueOf(maxValue));
	}
}
